from functools import wraps

from flask import g
from flask_login import AnonymousUserMixin

from apps.a_common.error import PremissionDenied
from apps.a_common.log import MyLogger
from apps.a_common.response import error_response

log = MyLogger('permission')


def has_permission(permission_name, user=None):
    log.info(f'user: {user}')
    user = g.user if user is None else user
    if user.is_anonymous:
        return False
    if user.id == 1:  # superuser
        return True

    from apps.users.helper import get_permissions_by_user_id
    permissions = get_permissions_by_user_id(user.id)
    if permission_name in [i.name for i in permissions]:
        return True
    return False


def has_permission_decorate(permission_name):
    def has_permission_function(func):
        @wraps(func)
        def wrapper(*args, **kw):
            if has_permission(permission_name):
                return func(*args, **kw)
            return error_response(PremissionDenied())

        return wrapper

    return has_permission_function


class AnonymousUser(AnonymousUserMixin):
    id = 0
